<?php

namespace app\factory\wxPay;

use think\facade\Config;
use app\libs\Util;

/**
 * 微信支付结果查询
 * Class CearteOrder
 * @package app\factory\wxPay
 */
class QueryOrder
{
    //小程序支付
    private $appid = "";//小程序appID
    private $mch_id = "";//商户号
    private $nonce_str;//随机字符串最高32位
    private $out_trade_no;//订单号
    private $sign;//签名
    private $key = "";//秘钥

    //构造
    public function __construct()
    {
        $this->appid = Config::get('system.wx_pay.app_id');//小程序id
        $this->mch_id = Config::get('system.wx_pay.mch_id');//获取小程序mch_id
        $this->key = Config::get('system.wx_pay.key');//获取小程序key
    }

    /**
     * 微信查询支付结果
     * @param string $pay_sn
     * @return bool|mixed|string
     */
    public function set_sign($pay_sn = '')
    {
        $this->nonce_str = md5(time());//生成随机字符串
        $this->out_trade_no = $pay_sn;//支付编号

        //ASCII排序
        $strA = "";
        $strA .= "appid=" . $this->appid;
        $strA .= "&mch_id=" . $this->mch_id;
        $strA .= "&nonce_str=" . $this->nonce_str;
        $strA .= "&out_trade_no=" . $this->out_trade_no;
        $strA .= "&key=" . $this->key;

        $this->sign = strtoupper(md5($strA));//转大写
        //xml数据
        $xml = "";
        $xml .= "<xml>";
        $xml .= "<appid>" . $this->appid . "</appid>";
        $xml .= "<mch_id>" . $this->mch_id . "</mch_id>";
        $xml .= "<nonce_str>" . $this->nonce_str . "</nonce_str>";
        $xml .= "<out_trade_no>" . $this->out_trade_no . "</out_trade_no>";
        $xml .= "<sign>" . $this->sign . "</sign>";
        $xml .= "</xml>";

        $url = "https://api.mch.weixin.qq.com/pay/orderquery";//访问微信支付查询url
        $wxpay = Util::post_request($url, $xml);//访问数据
        $wxpay = json_decode(json_encode(simplexml_load_string($wxpay, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
        return $wxpay;

    }

}